/* © 2007 Adobe Systems Incorporated. All rights reserved. */
package com.shubhjai.musiclib.managers
{
	import flash.events.EventDispatcher;
	import flash.data.SQLConnection;
	import flash.filesystem.File;
	import flash.events.SQLEvent;
	import flash.events.SQLErrorEvent;
	import com.shubhjai.musiclib.util.LogUtil;

	/**
	 * This singleton is a factory class for accessing SQLConnection objects
	 * to the databse. 
	 * 
	 * Note that in the AIR Runtime Beta 1 Release, we use a single SQLConnection 
	 * in order to avoid certain stability issues. In future releases it should be 
	 * possible to use a pool of SQLConnections, so that you can run a transaction 
	 * while simultaneously reading from the DB. 
	 */ 
	public class DatabaseConnectionManager extends EventDispatcher
	{
		
		private static var instance : DatabaseConnectionManager;
		
		private static const DBPATH : String = "tamilmusiclibrary.db";
		private var dbFile : File;
		
		private var conn : SQLConnection;
		
		/**
		 * Private constructor. Use getInstance() instead.
		 */
		public function DatabaseConnectionManager()
		{
			if ( instance != null )
			{
				throw new Error("Private constructor. Use getIntance() instead.");	
			}
			dbFile = File.applicationStorageDirectory.resolve( DBPATH );
			
		}
		
		/**
		 * Get an instance of the DataManager.
		 */ 
		public static function getInstance() : DatabaseConnectionManager
		{
			if ( instance == null )
			{
				instance = new DatabaseConnectionManager();
			}
			return instance;
		}
		
/**
		 * Get a new connection to the AdobeInside database. This also automatically opens the connection,
		 * passing the functions as listeners for the event. 
		 * 
		 * @param result The function to invoke when the connection is opened. Type SQLEvent
		 * @param error The function to invoke when an error occurs. Type SQLErrorEvent
		 */ 
		public function getConnection( result:Function, error:Function = null ) : SQLConnection
		{
			if ( error == null )
				error = onConnOpenError;
				
			if ( conn == null ) 
			{
				conn = new SQLConnection();
				conn.addEventListener( SQLEvent.OPEN, result );
				conn.addEventListener( SQLErrorEvent.ERROR, onConnOpenError );
				conn.open( dbFile );
			}
			//trace("getConn: " + conn.connected);
			
			/*
			var conn : SQLConnection = new SQLConnection();
			conn.addEventListener( SQLEvent.OPEN, result );
			conn.addEventListener( SQLErrorEvent.ERROR, status );
			conn.open( dbFile );
			*/
			
			return conn;
		}
		
		
		private function onConnOpenError( evt:SQLErrorEvent ) : void
		{
			LogUtil.getLogger(this).error( "Error opening database connection: " + evt );
		}
		
		
	}
}